package com.murphy.algorithm.stack;

/**
 *基于链表实现栈
 * @author dongsufeng
 * @date 2020/9/8 15:57
 * @version 1.0
 */
public class LinkedStack {

	private static class Node<E>{
		private E e;
		private Node<E> next;
		Node(E e,Node<E> next){
			this.e=e;
			this.next = next;
		}
	}
	private int count;
	private int num;
	private Node<String> head = null;
	LinkedStack(int count){
		this.count = count;
		this.num=0;
	}
	public boolean push(String item){
		if (num == count){
			return false;
		}
		Node<String> node = new Node<>(item,head);
		head = node;
		++num;
		return true;
	}

	public String pop(){
		if (num == 0){
			return null;
		}
		String e = head.e;
		head=head.next;
		--num;
		return e;
	}

	public static void main(String[] args) {
		LinkedStack linkedStack = new LinkedStack(4);
		linkedStack.push("111");
		linkedStack.push("222");
		linkedStack.push("333");
		linkedStack.push("444");
		linkedStack.push("555");
		System.out.println(linkedStack.head.e);
		int num = linkedStack.num;
		for (int i=0;i<num;i++) {
			System.out.println(linkedStack.pop());
		}
	}
}
